package com.rex.common.exception;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by frt on 2017/11/2.
 * 统一异常处理
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 处理自定义异常
     * @param request
     * @param exception
     * @return
     */
    @ExceptionHandler(value = BaseException.class)
    @ResponseBody
    public ErrorInfo<String> baseExceptionHandler(HttpServletRequest request, BaseException exception){
        ErrorInfo<String> errorInfo = new ErrorInfo<>();
        errorInfo.setMessage(exception.getMessage());
        errorInfo.setCode(ErrorInfo.ERROR);
        errorInfo.setData("自定义异常错误数据");
        errorInfo.setUrl(request.getRequestURI());
        return errorInfo;
    }

    /**
     * 处理其他异常
     * @param request
     * @param exception
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public ErrorInfo<String> exceptionHandler(HttpServletRequest request, Exception exception){
        ErrorInfo<String> errorInfo = new ErrorInfo<>();
        errorInfo.setMessage(exception.getMessage());
        errorInfo.setCode(ErrorInfo.ERROR);
        errorInfo.setData("其他异常错误数据");
        errorInfo.setUrl(request.getRequestURI());
        return errorInfo;
    }
}
